#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "Log.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"

namespace ThreadPoolModule
{
    using namespace ThreadModlue;
    using namespace LogModule;
    using namespace CondModule;
    using namespace MutexModule;

    static const int gnum = 5;
    template <typename T>
    class ThreadPool
    {
        private:
        void WakeUpAllThread()
        {
            LockGuard lockguard(_mutex);
            if(_sleepernum)
                _cond.Broadcast();
            LOG(LogLevel::INFO)<<"唤醒所有线程" ;   
        }

        void WakeUpOne()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << "唤醒一个休眠线程";
        }

        ThreadPool(int num=gnum):_num(num),_isrunning(false),_sleepernum(0)
        {
            for (size_t i = 0; i < num; i++)
            {
                _threads.emplace_back(
                    [this]()
                    {
                        HandlerTask();
                    }
                );
            }
            
        }
        void Start()
        {
            if(_isrunning)
            return;
            _isrunning=true;
            for(auto &thread:_threads)
            {
                thread.Start();
                LOG(LogLevel::INFO)<<"start new thread success: "<<thread.Name();
            }
        }
        public:
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;
        static ThreadPool<T> *GetInstance()
        {
            if(inc==nullptr)
            {
                LockGuard lockguard(_lock);
                LOG(LogLevel::DEBUG)<<"获取单例...";
                if(inc==nullptr)
                {
                    LOG(LogLevel::DEBUG)<<"首次使用单例，创建之...";
                    inc =new ThreadPool<T>();
                    inc->Start();
                }
            }
            return inc;
        }

        void Stop()
        {
            if(!_isrunning)
            return;
            _isrunning=false;
            //唤醒所有线程
            WakeUpAllThread();
        }

        void Join()
        {
            for(auto &thread:_threads)
            {
                thread.Join();
            }
        }

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(),name,sizeof(name));
            while(true)
            {
                T t;
                {
                    LockGuard lockguard(_mutex);
                    //只有当队列为空且线程池没有退出才会去休眠
                    while (_taskq.empty()&&_isrunning)
                    {
                        _sleepernum++;
                        _cond.Wait(_mutex);
                        _sleepernum--;
                    }
                    //2.走到这里说明内部线程被唤醒，但是这里唤醒可能是因为线程池退出无法wait
                    if(!_isrunning&&_taskq.empty())
                    {
                        //队列没有任务时线程池才能退出
                         LOG(LogLevel::INFO) << name << " 退出了, 线程池退出&&任务队列为空";
                         break;
                    }

                    //走到这里说明一定有任务
                    t=_taskq.front();
                    _taskq.pop();
                }
                t();//处理任务，非临界区
            }
        }

        bool Enqueue(const T &in)
        {
            if(_isrunning)//不加锁是因为修改running状态时,一般不会有线程再调用这个函数
            {
                LockGuard lockguard(_mutex);
                _taskq.push(in);
                if(_threads.size()==_sleepernum)
                    WakeUpOne();
                return true;
            }
            return false;
        }

        ~ThreadPool()
        {}
        private:
        std::vector<Thread> _threads;
        int _num;//线程个数
        std::queue<T> _taskq;//任务队列
        Cond _cond;
        Mutex _mutex;

        bool _isrunning;
        int _sleepernum;
        static ThreadPool<T> *inc;//单列指针
        static Mutex _lock;//懒汉模式下的锁
    };
    template <typename T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr;

    template <typename T>
    Mutex ThreadPool<T>::_lock;
}